package oot.activity;

import java.util.regex.Pattern;

import oot.data.Config;
import oot.data.Connection;
import oot.data.JSonPaser;
import oot.data.User;
import oot.tab.activity.FragmentTabs;
import oot.tab.activity.R;
import oot.tab.activity.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class LoginActivity extends Activity {
	public static final String SERVER_ADDRESS = "http://192.168.1.10/";
	
	private String email;
	private String passwd;
	private EditText editTextEmail;
	private EditText editTextPassword;
	private Button loginButton;
	private JSONObject js;
	private ProgressDialog progressDialog;

	private Button registerButton;

	private static String regId;


	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		/** For notification service **/
		//GCMRegistrar.checkDevice(this);
		//GCMRegistrar.checkManifest(this);
		regId = GCMRegistrar.getRegistrationId(this);

		if (regId.equals("")) {
		  GCMRegistrar.register(this, Utils.GCMSenderId);
		} else {
		  Log.v("TAG", "Already registered");
		}
		/** End of notification **/
		
		progressDialog = new ProgressDialog(this);
		getIntent().setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		editTextEmail = (EditText) findViewById(R.id.et_email);
		editTextPassword = (EditText) findViewById(R.id.et_password);
		registerButton = (Button)findViewById(R.id.bt_register);
		registerButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(),RegisterActivity.class);
				startActivity(i);
			}
		});
		editTextEmail.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (!hasFocus) {
					email = editTextEmail.getText().toString();
					if (email.length() < 1) {
						Toast toast = Toast.makeText(getApplicationContext(),
								"Email not be blank", Toast.LENGTH_SHORT);
						toast.show();
					} else if (!validateEmail(email)) {
						Toast toast = Toast.makeText(getApplicationContext(),
								"Email not validated", Toast.LENGTH_SHORT);
						toast.show();
					}
				}
			}
		});
		editTextPassword.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (!hasFocus) {
					passwd = editTextEmail.getText().toString();
					if (passwd.length() < 1) {
						Toast toast = Toast.makeText(getApplicationContext(),
								"Passwd not be blank", Toast.LENGTH_SHORT);
						toast.show();
					}
				}
			}
		});
		loginButton = (Button) findViewById(R.id.bt_login);
		loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				passwd = editTextPassword.getText().toString();
				email = editTextEmail.getText().toString();
				if (email.length() < 1 || passwd.length() < 1) {
					Toast toast = Toast.makeText(getApplicationContext(),
							"Passwd and Username not be blank",
							Toast.LENGTH_SHORT);
					toast.show();
					return;
				}
				doLogin(email, passwd);
				progressDialog.setMessage("logging...");
				progressDialog.show();
				// Intent i = new
				// Intent(getApplicationContext(),FragmentTabs.class);
				// startActivity(i);

			}
		});
	}

	private static final Pattern patten = Pattern
			.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]" + "+(?:\\.[a-z0-9!#$%&'*"
					+ "+/=?^_`{|}~-]+)*"
					+ "@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)"
					+ "+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");

	public boolean validateEmail(String email) {

		if (!patten.matcher(email.trim()).matches()) {
			return false;
		} else {
			return true;
		}

	}

	public void onBackPressed() {
		super.onBackPressed();
		this.finish();
	}
	
	private void doLogin(String _username, String _passwd) {
		RequestParams params = new RequestParams();
		params.put("username", _username);
		params.put("password", _passwd);
		params.put("regId", regId);
		Log.i("test", "params :" + params.toString());
		//Connection.setBaseURL("http://192.168.1.9/");
		Connection.post("users/login", params,
				new AsyncHttpResponseHandler() {
					public void onSuccess(String arg0) {
						Log.i("test", "return --------" + arg0);
						if (progressDialog.isShowing()) {
							progressDialog.dismiss();
						}
						super.onSuccess(arg0);
						try {
							js = new JSONObject(arg0);
							// Log.i("test",)
							if (js.getInt("status_code") != 0) {
								// show error message if error occur
								try {
									Animation shake = AnimationUtils
											.loadAnimation(
													getApplicationContext(),
													R.anim.shake);
									loginButton.startAnimation(shake);
									Toast toast = Toast.makeText(
											getApplicationContext(),
											js.getString("message"),
											Toast.LENGTH_SHORT);
									toast.show();

								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							} else {
								// save user information to use later
								SharedPreferences sharedPreferences = getSharedPreferences(
										"login", MODE_PRIVATE);
								SharedPreferences.Editor editor = sharedPreferences
										.edit();
								//JSONObject jss = js.getJSONObject("entity");
								User saveUser = JSonPaser.paserUser((js.getJSONObject("entity")).getJSONObject("User"));
								FlashScreenActivity.user = saveUser;
								editor.putBoolean("logedin", true);
								editor.putString(Config.ACCESSTOKEN, saveUser.getAccesstoken());
								editor.putString(Config.USER_ID, saveUser.getUserID());
								editor.putString(Config.USER_NAME, saveUser.getUserName());
								editor.putString(Config.USER_SCREEN_NAME, saveUser.getUserScreenName());
								editor.putString(Config.USER_AVATA_URL, saveUser.getUserAvatarURL());
								Connection.accesstoken = saveUser.getAccesstoken();
								editor.commit();
								Intent i = new Intent(getApplicationContext(),
										FragmentTabs.class);
								i.putExtra("user", FlashScreenActivity.user);
								startActivity(i);
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(Throwable arg0, String arg1) {
						// TODO Auto-generated method stub
						super.onFailure(arg0, arg1);
						Log.e("Faile","On Faile");
						if(progressDialog.isShowing()){
							progressDialog.dismiss();
							Toast.makeText(getApplicationContext(), "Login faile", Toast.LENGTH_LONG).show();
						}
					}
				});
	}

}
